<?php 
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use app\model\UserModel;
use app\Common;
use app\controller\Token;

//控制器
class Msg {
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    var $customers = [];
    var $status = [1=>'未读',2=>'已读',3=>'已回复'];
    var $type=[1=>'咨询',2=>'投诉',3=>'系统提醒',4=>'聊天'];

    public function __call($method, $args){
        
    }

    public function __construct(){

        $um=new UserModel();
        $this->users = $um->getAll();

        // $custs =Db::table('customer')->where('status',1)->select()->toArray();
        // // foreach($custs as $cust){
        // //     $this->customers[$cust['id']] = $cust['name'];
        // // }
        // unset($custs);


    }    

    //后台消息管理
    public function index(){
        $uid=Session::get('logonid');

        if(empty($uid)) {
            return header("location:/index.php/login/customer_login"); 
        }
        $all = Request::param();

        $type='';
        $text='';
        $list = Db::table('msg')->where('customer_id','>',0);
        
        if(!empty($all['type'])){
           $type =$all['type'];        
           $list =$list->where('type','in',$type);
        }

        if(!empty($all['text'])){
            $text =$all['text'];
            $list =$list->where('text','like','%'.$text.'%');
        }

        $list =$list->order('create_time','desc')->paginate(30)->toArray();

        foreach($list['data'] as &$kv){
            $kv['customer_id_name'] =Db::table('customer')->where('id',$kv['customer_id'])->value('name');
            $kv['status_name']  =$this->status[$kv['status']];
            $kv['imgs'] = explode(",",$kv['img']);
            $kv['type_name'] = $this->type[$kv['type']];

            foreach($kv['imgs'] as &$img){
                $img =  str_replace("\"","",str_replace("]","",str_replace("[","",$img)));
            }
            $kv['res'] = Db::table('msg')->where('answer_to',$kv['id'])->select()->toArray();
            foreach($kv['res'] as &$res){
                $res['user_id_name'] = $this->users[$res['user_id']]['name'];
                $res['status_name'] = $this->status[$res['status']];
            }

        }

        View::assign(['type'=>$type,'text'=>$text,'list'=>$list]);
        return View::fetch('msg_index');
    }


    //通用的上传方法
    public function upload_x(){

        $all = Request::param();

        $files = $_FILES;

        if(count($files)<1) return json(['code'=>0,'msg'=>'Error!']);

        $res =[];
        foreach($files as $file){
            $up =Common::upload($file);
            if($up['code']==1){
                $res[] =$up;
            }else{
                return json($up);
            }
        }
        return json($res);

    }

    //消息提交
    public function msg_post($value=''){
        $uid=Session::get('logonid');
        $all = Request::param();

        if(empty($all['content'])){
            return json(['code'=>0,'msg'=>'没有内容提交!']);
        }

        //app端提交
        if(!empty($all['token'])){

            $token = new token();
            $arr = $token->check_token($all['token']); 

            if($arr['code']<1){
                return json($arr);
            }
            $customer_id=$arr['customer']['id'];

            if(!empty($all['img'])){
                $img = str_replace("\"","",str_replace("]","",str_replace("[","",$all['img'])));
            }else{
                $img='';
            }

            $arr = array(
                'type'=>$all['type'],
                'text' =>$all['content'],
                'img' =>$img,
                'customer_id'=>$uid?'':$customer_id,
                'create_time'=>date('Y-m-d H:i:s'),
                'status'=>1
            );

            Db::table('msg')->insert($arr);
            return json(['code'=>1,'msg'=>'ok']);

        }

        if(empty($uid)) return header('/index.php/login/index/target/admin');
        
        $cust_id = Db::table('msg')->where('id',$all['to'])->value('customer_id');

        $arr = array(
            'type'=>4,
            'text' =>'回复:'.$all['content'],
            'user_id'=>$uid,
            'answer_to' => $all['to'],  //需要回复的消息id
            'to' => $cust_id,           //客户id
            'create_time'=>date('Y-m-d H:i:s'),
            'status'=>2
        );
        $res =Db::table('msg')->insert($arr);
        if($res){
            Db::table('msg')->update(['id'=>$all['to'],'status'=>3]);
        }

        return json(['code'=>1,'msg'=>'ok']);

    }


    public function msg_count(){
        $uid=Session::get('logonid');
        
        if(empty($uid)) {
            return header("location:/index.php/login"); 
        }
        $all = Request::param();
        $list =Db::query('select count(id) as cnt from msg where status=1 and type in(1,2,3) ');

        return json(['code'=>1,'count'=>$list[0]['cnt']]);

    }

    //我的咨询回复
    public function res_msg(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'请登录！']);
        }        
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }
        $customer =$arr['customer'];

        $sql ="select id,user_id,text,status,create_time from msg where customer_id =  ? order by create_time desc limit 50 "; 
        $msgs = Db::query($sql,[$customer['id']]);

        $new_msg=0;
        foreach($msgs as &$row){
            $sql ="select id,user_id,status,text,create_time from msg where `answer_to` =  ? order by create_time desc limit 50"; 
            $row['answer'] = Db::query($sql,[$row['id']]);
            foreach($row['answer'] as $row2){
                if($row2['status']==1) $new_msg+=1;            
            }
        }


        if(!empty($all['get_count'])) $msgs=[];
        return json(['code'=>1,'new_msg'=>$new_msg,'data'=>$msgs]);
    }

    //设置已读
    function set_readed(){
        $uid=Session::get('logonid');
        $all = Request::param(); 
        if(empty($uid)) {
            if(empty($all['token'])){
                return header("location:/index.php/login/customer_login"); 
            }

            $token = new Token();
            $arr = $token->check_token($all['token']);
            if(!$arr['code']){
                return json($arr['msg']);
            }
            $customer=$arr['customer'];

            $sql ="update msg set status=2 where status=1 and `answer_to` = ?";
            Db::execute($sql,[$customer['id']]);
            return json(['code'=>1,'msg'=>'ok']);
        }
        


        $id = !empty($all['id'])?$all['id']:''; 
        if(!$id) return json(['code'=>0,'msg'=>'消息没有啊']);

        $row = Db::table('msg')->find($id);
        $row['status']=3;
        Db::table('msg')->update($row);

        return json(['code'=>1,'msg'=>'消息已读!']);

    }


    public function msg_remove(){

        $uid=Session::get('logonid');
        $all = Request::param();

        if(empty($uid)) {
            return header("location:/index.php/login/customer_login"); 
        }
        if(!$all['id']){
            return;
        }

        $res =Db::table('msg')->where('id',$all['id'])->delete();
        if($res){
            return json_encode(['code'=>1,'msg'=>'ok']);
        }
        return json_encode(['code'=>0,'msg'=>'failed']);
    }


    public function msg_group(){
        $uid=Session::get('logonid');
        if(empty($uid)) {
            return header("location:/index.php/login/customer_login"); 
        }        
        $all = Request::param();

        $sql = "select customer_id,count(id) as cnt from msg where `to`=1075 and status=1 group by customer_id";
        $list =Db::query($sql);

        foreach($list as &$item){
            $item['customer_name']=Db::table('customer')->where('id',$item['customer_id'])->value('name');
        }

        return json_encode(['code'=>1,'data'=>$list]);

    }

}